package com.mzj.saas.mservice.house.service;

import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.enums.LockAuditTypeEnum;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.house.entity.LockAudit;
import com.mzj.saas.mservice.house.repository.CohabitRepository;
import com.mzj.saas.mservice.house.repository.HouseMatchUserRepository;
import com.mzj.saas.mservice.house.repository.LockAuditRepository;
import com.mzj.saas.mservice.house.repository.LockFrozenRepository;
import com.mzj.saas.mservice.house.vo.LockAuditVO;
import com.mzj.saas.mservice.lock.entity.LockFrozen;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class LockService {
    private static final Logger log = LoggerFactory.getLogger(LockService.class);

    @Autowired
    private LockAuditRepository lockAuditRepository;
    @Autowired
    private CohabitRepository cohabitRepository;
    @Autowired
    private LockFrozenRepository lockFrozenRepository;
    @Autowired
    private HouseMatchUserRepository houseMatchUserRepository;
    @Autowired
    private RedisService redisService;

    /*public ResultBean<List<LockAuditVO>> findLockAudit2(String houseId) {
        try {
            if (StringUtils.isBlank(houseId)) {
                return ResultBean.failedResultOfParamWithMsg("公租房ID为空");
            }

            List<LockAudit> list = lockAuditRepository.findByHouseId(houseId);
            //授权信息为空
            if (list == null || list.size() == 0) {
                //新增承租人授权信息
                HouseMatchUser match = houseMatchUserRepository.findByHouseIdAndStatus(houseId, 1);
                LockAudit lockAudit = new LockAudit();
                lockAudit.setHouseId(houseId);
                lockAudit.setMatchUserId(match.getMatchUserId());
                //lockAudit.setAuditId(match.getMatchUserId());
                lockAudit.setStatus(LockAuditTypeEnum.UN_AUTHORIZE.getValue());
                lockAuditRepository.save(lockAudit);
                list.add(lockAudit);
                //新增同住人授权信息
                List<Cohabit> cohabits = cohabitRepository.findByApplyId(match.getApplyId());
                for (Cohabit cohabit : cohabits) {
                    LockAudit audit = new LockAudit();
                    audit.setHouseId(houseId);
                    audit.setMatchUserId(match.getMatchUserId());
                    //audit.setAuditId(cohabit.getId());
                    audit.setStatus(LockAuditTypeEnum.UN_AUTHORIZE.getValue());
                    lockAuditRepository.save(audit);
                    list.add(audit);
                }
            }

            List<LockAuditVO> listvo = new ArrayList<>();
            for (LockAudit lockAudit : list) {
                LockAuditVO lockAuditVO = new LockAuditVO();
                //承租人情况
                if (lockAudit.getMatchUserId().equals(lockAudit.getAuditId())) {
                    AppUser user = appUserRepository.findByIdAndStatus(lockAudit.getMatchUserId(), 1);
                    lockAuditVO.setName(user.getName());
                    lockAuditVO.setPhone(user.getPhone());
                    lockAuditVO.setAuditType(1);
                    lockAuditVO.setFamilyTies(1);
                } else {//同住人情况
                    Optional<Cohabit> optional = cohabitRepository.findById(lockAudit.getAuditId());
                    if (optional.isPresent()) {
                        Cohabit cohabit = optional.get();
                        lockAuditVO.setName(cohabit.getName());
                        lockAuditVO.setPhone(cohabit.getMobile());
                        lockAuditVO.setAuditType(2);
                        lockAuditVO.setFamilyTies(cohabit.getFamilyTiesType());
                    }
                }
                lockAuditVO.setId(lockAudit.getId());
                lockAuditVO.setMatchUserId(lockAudit.getMatchUserId());
                //lockAuditVO.setAuditId(lockAudit.getAuditId());
                lockAuditVO.setHouseId(lockAudit.getHouseId());
                lockAuditVO.setStatus(lockAudit.getStatus());
                lockAuditVO.setType(lockAudit.getType());
                lockAuditVO.setOperationId(lockAudit.getOperationId());
                lockAuditVO.setAuditTime(lockAudit.getAuditTime());

                listvo.add(lockAuditVO);
            }
            return ResultBean.successfulResult(listvo);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }*/

    public ResultBean<List<LockAuditVO>> findLockAudit(String houseId) {
        try {
            if (StringUtils.isBlank(houseId)) {
                return ResultBean.failedResultOfParamWithMsg("公租房ID为空");
            }

            List<LockAudit> list = lockAuditRepository.findByHouseId(houseId);


            return ResultBean.successfulResult(null);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    public ResultBean<Object> authorize(String accessToken, Long id) {
        try {
            //根据token获取用户信息
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfParamWithMsg(null);
            }

            String userId = tokenRedisVo.getId();//用户id

            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("id为空");
            }

            Optional<LockAudit> optional = lockAuditRepository.findById(id);
            if (!optional.isPresent()) {
                return ResultBean.failedResultWithMsg("授权信息不存在");
            }

            LockAudit lockAudit = optional.get();
            lockAudit.setStatus(LockAuditTypeEnum.AUTHORIZE.getValue());
            lockAudit.setOperationId(userId);
            lockAudit.setAuditTime(new Date());

            return ResultBean.successfulResult(null);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }

    }

    @Transactional
    public ResultBean<Object> freeze(String accessToken,String houseId, String reason) {
        try {
            //根据token获取用户信息
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfParamWithMsg(null);
            }

            String id = tokenRedisVo.getId();//用户id

            if (houseId == null) {
                return ResultBean.failedResultOfParamWithMsg("ID为空");
            }

            if (StringUtils.isBlank(reason)) {
                return ResultBean.failedResultOfParamWithMsg("冻结原因为空");
            }

            lockAuditRepository.updateByHouseId(houseId, LockAuditTypeEnum.FREEZE.getValue());//更新状态为已冻结

            LockFrozen lockFrozen = new LockFrozen();
            lockFrozen.setHouseId(houseId);
            //ResultBean<AppUser> matchUser = checkService.findMatchUser(accessToken, houseId);
            //lockFrozen.setMatchUserId(matchUser.getResultData().getId());
            lockFrozen.setOperationId(id);
            lockFrozen.setOperationTime(new Date());
            //lockFrozen.setReason(reason);

            lockFrozenRepository.save(lockFrozen);//新增智能锁冻结明细

            return ResultBean.successfulResult(null);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    @Transactional
    public ResultBean<Object> unfreeze(String houseId) {
        try {
            if (houseId == null) {
                return ResultBean.failedResultOfParamWithMsg("ID为空");
            }

            lockAuditRepository.updateByHouseId(houseId, LockAuditTypeEnum.UN_FREEZE.getValue());//更新状态为已解冻

            return ResultBean.successfulResult(null);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }

    }


}
